package com.example.doer.reading.AppActivities;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.fragment.AbFragment;
import com.ab.http.AbHttpUtil;
import com.ab.http.AbStringHttpResponseListener;
import com.example.doer.reading.AppAdapters.MyTopicAdapter;
import com.example.doer.reading.AppDataModel.Topic;
import com.example.doer.reading.AppDataModel.TopicReply;
import com.example.doer.reading.R;
import com.example.doer.reading.global.MyApplication;
import com.example.doer.reading.myHome.layout.SmartRefreshLayout;
import com.example.doer.reading.myHome.layout.api.RefreshLayout;
import com.example.doer.reading.myHome.layout.listener.OnLoadmoreListener;
import com.example.doer.reading.myHome.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static android.os.SystemClock.sleep;
import static com.ab.util.AbToastUtil.showToast;
import static com.google.android.gms.internal.zzagz.runOnUiThread;

/**
 * Created by 严旭江 on 2017/7/11.
 */

//话题---为一个碎片
public class FragmentTwo extends AbFragment {
    //上拉进行刷新
    private SmartRefreshLayout smartRefreshLayout = null;
    private ListView listView;
    MyTopicAdapter myTopicAdapter;
    Toolbar mToolbar;
    static int count ;//listView中的数目  动态添加
    List<Topic> topicList = new ArrayList<Topic>();
    String UserID;//使用软件的人的UserID  通过全局获得
    static boolean hasCreteAvtivity;
    /**
     * 隐藏ToolBar的三个对象
     */
    private float scaledTouchSlop;
    private float firstY = 0;
    private ObjectAnimator animtor;
    AbHttpUtil abHttpUtil;

    public FragmentTwo(){

    }
    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState){
        View view=inflater.inflate(R.layout.fragment_topic, container, false);
        abHttpUtil =AbHttpUtil.getInstance(getActivity());
        //获取fragment_topic中的ListView的引用
        listView = (ListView)view.findViewById(R.id.topic_list);
        listView.setPadding(2,2,2,2);
        /**
         * ToolBar的使用
         */
        mToolbar = (Toolbar)view.findViewById(R.id.fragment_two_toolBar);
        //取代原本的actionbar
        /**
         * getActivity().setSupportActionBar(mToolbar);//bug 需要继承AppCompatActivity
         */

        /**
         * 搜索与提问的点击事件
         */
        TextView searchBtn = (TextView) view.findViewById(R.id.askQuestion_tv);
        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**
                 * 跳转Activity
                 */
                Intent intent = new Intent(getActivity(),AskQuestionActivity.class);
                //1001为请求码
                startActivityForResult(intent,1001);
                //startActivity(intent);
            }
        });
        /**
         * 搜索按钮点击功能
         */
        view.findViewById(R.id.searchCommitBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText et = (EditText)mToolbar.findViewById(R.id.searchContent);
                String s = et.getText().toString();
                if(!TextUtils.isEmpty(s.trim())) {
                    /**
                     * 搜索跳转
                     */
                    Intent intent = new Intent(getActivity(),SearchResultActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("searchKey",s.trim());
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
                else{
                    Toast.makeText(getActivity(),"Iuput Cannot Be NULL",Toast.LENGTH_SHORT).show();
                }
            }
        });
//        if(!hasCreteAvtivity) {
            /**
             * 获取服务器传来的数据
             */
            String UserID = MyApplication.user.getUserID();
            String getJSONObjectRUL = "http://192.168.191.1/Reading/QuestionServlet?Action=downMainInterface&userID=" + UserID;
            abHttpUtil.get(getJSONObjectRUL,
                    new AbStringHttpResponseListener() {
                        @Override
                        public void onSuccess(int i, String s) {
                            /**
                             * s即传递过来的json打包数据
                             */
                            try {
                                JSONArray jsonArray = new JSONObject(s).getJSONArray("MainInterface");
                                //创建Topic的对象集合
                                Topic addTopic;
                                TopicReply addTopicReply;
                                for (int j = 0; j < jsonArray.length(); j++) {
                                    /**
                                     * 获取数据封装成对象
                                     */
                                    if (count < 10) {
                                        JSONObject jsonObject = (JSONObject) jsonArray.get(j);
                                        //Theme名字  一级
                                        String themeName = jsonObject.getString("QuestionFromTopicName");
                                        String themeLogoPath = jsonObject.getString("topic_logo");
                                        //问题名字   二级
                                        String topicName = jsonObject.getString("QuestTitle");
                                        String topicID = jsonObject.getString("QuestID");
                                        String topicDesc = jsonObject.getString("QuestDescription");
                                        String topicFavourCount = jsonObject.getString("QuestionFocusCount");
                                        String topicCollectCount = jsonObject.getString("QuestionAnswerCount");
                                        //第三级对象  Answer--->对应本代码 TopicReply
                                        /**
                                         * 判断传送过来的thirdObj是否为空
                                         */
                                        if (!jsonObject.isNull("answer")) {
                                            JSONObject thirdObj = (JSONObject) jsonObject.get("answer");
                                            String thirdObjID = thirdObj.getString("AnswerID");
                                            String thirdObjFromTopicID = thirdObj.getString("AnswerFromQuestID");
                                            String thirdObjContent = thirdObj.getString("AnswerContent");
                                            //额外新增 回复的用户名
                                            String thirdObjUserName = thirdObj.getString("AnswerFromUserName");
                                            String thirdObjUserID = thirdObj.getString("AnswerFromUserID");
                                            String thirdObjFavourCount = thirdObj.getString("ThumbUpCount");
                                            String thirdObjReplyCount = thirdObj.getString("ReplyCount");
                                            String thirdObjCollectCount = thirdObj.getString("UserCollectCount");
                                            boolean thirdObjIsThumbUp = thirdObj.getBoolean("IsThumbUp");
                                            boolean thirdObjIsCollect = thirdObj.getBoolean("IsCollect");
                                            addTopicReply = new TopicReply(thirdObjID, thirdObjFromTopicID, thirdObjUserID, thirdObjUserName, thirdObjContent, Integer.valueOf(thirdObjFavourCount), Integer.valueOf(thirdObjCollectCount), Integer.valueOf(thirdObjReplyCount), thirdObjIsThumbUp, thirdObjIsCollect);
                                            addTopic = new Topic(topicID, themeName, themeLogoPath, topicName, topicDesc, Integer.valueOf(topicCollectCount), Integer.valueOf(topicFavourCount), addTopicReply);
                                            topicList.add(addTopic);
                                        } else {
                                            //说明问题没有回答
                                            addTopic = new Topic(topicID, themeName, themeLogoPath, topicName, topicDesc, Integer.valueOf(topicCollectCount), Integer.valueOf(topicFavourCount));
                                            topicList.add(addTopic);
                                        }
                                        count++;
                                    }//end if
                                    else break;
                                }//end for
                                //初始化count
                                count = 0;
                                myTopicAdapter = new MyTopicAdapter(getActivity(), topicList, R.layout.topic_listview);
                                listView.setAdapter(myTopicAdapter);
                            } catch (JSONException e) {
                                count = 0;
                                e.printStackTrace();
                            }

                        }//end onSuccess

                        @Override
                        public void onStart() {

                        }

                        @Override
                        public void onFinish() {

                        }

                        @Override
                        public void onFailure(int i, String s, Throwable throwable) {
                            showToast(getActivity(), "fragment_2获取数据时，连接服务器失败");
                        }
                    });
//            hasCreteAvtivity = !hasCreteAvtivity;
//        }

        //判断认为是滑动的最小距离(乘以系数调整滑动灵敏度)
        scaledTouchSlop = ViewConfiguration.get(getActivity()).getScaledTouchSlop()*3.0f;
        /**
         * 添加一个HeadView避免第一个Item被ToolBar遮挡
         * 必须在setAdapter之前进行设置
         */
        //initHeadView();
        /**
         * listView触摸监听事件
         */
//        listView.setOnTouchListener(new View.OnTouchListener() {
//            private float currentY;
//            private int direction=-1;
//            private boolean mShow = true;
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                switch (event.getAction()){
//                    case MotionEvent.ACTION_DOWN:
//                        firstY = event.getY();
//                        break;
//                    case MotionEvent.ACTION_MOVE:
//                        currentY = event.getY();
//                        //向下滑动
//                        if (currentY - firstY > scaledTouchSlop) {direction = 0;}
//                        //向上滑动
//                        else if (firstY - currentY > scaledTouchSlop) {direction=1;}
//                        //如果是向上滑动，并且ToolBar是显示的，就隐藏ToolBar
//                        if (direction == 1) {
//                            if (mShow) {
//                                toobarAnim(1);
//                                mShow = !mShow;
//                            }
//                        }else if (direction == 0) {
//                            if (!mShow) {
//                                toobarAnim(0);
//                                mShow = !mShow;
//                            }
//                        }
//                        break;
//                    case MotionEvent.ACTION_UP:
//                        break;
//                }//end switch
//                //不能返回true，如果返回true,onTouchEvent就无法执行，导致的后果是ListView无法滑动
//                return false;
//            }
//        });

        //下滑刷新
        smartRefreshLayout=(SmartRefreshLayout) view.findViewById(R.id.PullRefreshView_topic);
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refresh();
            }
        });
        smartRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                download();
            }
        });

        return view;
    }//end methos onCreateView

    /**
     * @param requestCode 当前界面只有一个跳转  故
     * @param resultCode 根据提问题结果 返回两种resultCode  2001-->返回或者失败 2002 成功 传递数据过来
     * @param data 即传递过来的Intent对象  可以获取传递过来的数据
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode){
            case 2001:{//返回
                break;
            }
            case 2002:{//确定
                String queName = AskQuestionActivity.content;
                String queDesc = AskQuestionTwoActivity.questionDesc;
                String theme = AskQuestionTwoActivity.chooseTheme;
                String UserID = MyApplication.user.getUserID();
                String url = "http://192.168.191.1/Reading/QuestionServlet?Action=up&userID="
                        +UserID+"&QuestionFromTopicName="+theme+"&questTitle="+queName+"&questDescription="+queDesc;
                abHttpUtil.get(url, new AbStringHttpResponseListener() {
                    @Override
                    public void onSuccess(int i, String s) {
                        showToast(getActivity(),"连接服务器成功");
                    }

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onFinish() {

                    }

                    @Override
                    public void onFailure(int i, String s, Throwable throwable) {
                        showToast(getActivity(),"提出问题时，连接服务器失败");
                    }
                });
                break;
            }
        }
    }

    /**
     * 下滑刷新
     */
    private void refresh(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                sleep(2000);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        UserID = MyApplication.user.getUserID();
                        String getJSONObjectRUL = "http://192.168.191.1/Reading/QuestionServlet?Action=downMainInterface&userID="+UserID;
                        abHttpUtil.get(getJSONObjectRUL, new AbStringHttpResponseListener() {
                            @Override
                            public void onSuccess(int i, String s) {
                                try {
                                    JSONArray jsonArray = new JSONObject(s).getJSONArray("MainInterface");
                                    //创建Topic的对象集合
                                    Topic addTopic;
                                    TopicReply addTopicReply;
                                    for(int j = 0;j<jsonArray.length();j++){
                                        topicList.clear();
                                        /**
                                         * 获取数据封装成对象
                                         */
                                        if (count<10) {
                                            JSONObject jsonObject = (JSONObject) jsonArray.get(j);
                                            //Theme名字  一级
                                            String themeName = jsonObject.getString("QuestionFromTopicName");
                                            String themeLogoPath = jsonObject.getString("topic_logo");
                                            //问题名字   二级
                                            String topicName = jsonObject.getString("QuestTitle");
                                            String topicID = jsonObject.getString("QuestID");
                                            String topicDesc = jsonObject.getString("QuestDescription");
                                            String topicFavourCount = jsonObject.getString("QuestionFocusCount");
                                            String topicCollectCount = jsonObject.getString("QuestionAnswerCount");
                                            //第三级对象  Answer--->对应本代码 TopicReply
                                            /**
                                             * 判断传送过来的thirdObj是否为空
                                             */
                                            if (!jsonObject.isNull("answer")) {
                                                JSONObject thirdObj = (JSONObject) jsonObject.get("answer");
                                                String thirdObjID = thirdObj.getString("AnswerID");
                                                String thirdObjFromTopicID = thirdObj.getString("AnswerFromQuestID");
                                                String thirdObjContent = thirdObj.getString("AnswerContent");
                                                String thirdObjUserName = thirdObj.getString("AnswerFromUserName");
                                                String thirdObjUserID = thirdObj.getString("AnswerFromUserID");
                                                String thirdObjFavourCount = thirdObj.getString("ThumbUpCount");
                                                String thirdObjReplyCount = thirdObj.getString("ReplyCount");
                                                String thirdObjCollectCount = thirdObj.getString("UserCollectCount");
                                                boolean thirdObjIsThumbUp = thirdObj.getBoolean("IsThumbUp");
                                                boolean thirdObjIsCollect = thirdObj.getBoolean("IsCollect");
                                                addTopicReply = new TopicReply(thirdObjID,thirdObjFromTopicID,thirdObjUserID,thirdObjUserName,thirdObjContent,Integer.valueOf(thirdObjFavourCount),Integer.valueOf(thirdObjCollectCount),Integer.valueOf(thirdObjReplyCount),thirdObjIsThumbUp,thirdObjIsCollect);
                                                addTopic = new Topic(topicID,themeName,themeLogoPath,topicName,topicDesc,Integer.valueOf(topicCollectCount),Integer.valueOf(topicFavourCount),addTopicReply);
                                                topicList.add(addTopic);
                                            }
                                            else {
                                                //说明问题没有回答
                                                addTopic = new Topic(topicID,themeName,themeLogoPath,topicName,topicDesc,Integer.valueOf(topicCollectCount),Integer.valueOf(topicFavourCount));
                                                topicList.add(addTopic);
                                            }
                                            count ++;
                                        }//end if
                                        else break;
                                    }//end for
                                    //初始化count
                                    count = 0;
                                    myTopicAdapter.notifyDataSetChanged();
                                    //myTopicAdapter = new MyTopicAdapter(getActivity(),topicList,R.layout.topic_listview);
                                    //listView.setAdapter(myTopicAdapter);
                                } catch (JSONException e) {
                                    count = 0;
                                    e.printStackTrace();
                                }
                                smartRefreshLayout.finishRefresh();
                            }

                            @Override
                            public void onStart() {

                            }

                            @Override
                            public void onFinish() {

                            }

                            @Override
                            public void onFailure(int i, String s, Throwable throwable) {
                                smartRefreshLayout.finishRefresh();
                                showToast(getActivity(),"刷新时 连接服务器失败");
                            }
                        });

                    }
                });
            }
        }).start();
    }
    /**
     * 上滑加载
     */
    private void download(){
        new Thread(new Runnable(){
            @Override
            public void run(){
                sleep(2000);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        UserID = MyApplication.user.getUserID();
                        String getJSONObjectRUL = "http://192.168.191.1/Reading/QuestionServlet?Action=downMainInterface&userID="+UserID;
                        abHttpUtil.get(getJSONObjectRUL, new AbStringHttpResponseListener() {
                            @Override
                            public void onSuccess(int i, String s) {
                                try {
                                    JSONArray jsonArray = new JSONObject(s).getJSONArray("MainInterface");
                                    //创建Topic的对象集合
                                    Topic addTopic;
                                    TopicReply addTopicReply;
                                    for(int j = 0;j<jsonArray.length();j++){
                                        /**
                                         * 获取数据封装成对象
                                         */
                                        if (count<10) {
                                            JSONObject jsonObject = (JSONObject) jsonArray.get(j);
                                            //Theme名字  一级
                                            String themeName = jsonObject.getString("QuestionFromTopicName");
                                            String themeLogoPath = jsonObject.getString("topic_logo");
                                            //问题名字   二级
                                            String topicName = jsonObject.getString("QuestTitle");
                                            String topicID = jsonObject.getString("QuestID");
                                            String topicDesc = jsonObject.getString("QuestDescription");
                                            String topicFavourCount = jsonObject.getString("QuestionFocusCount");
                                            String topicCollectCount = jsonObject.getString("QuestionAnswerCount");
                                            //第三级对象  Answer--->对应本代码 TopicReply
                                            /**
                                             * 判断传送过来的thirdObj是否为空
                                             */
                                            if (!jsonObject.isNull("answer")) {
                                                JSONObject thirdObj = (JSONObject) jsonObject.get("answer");
                                                String thirdObjID = thirdObj.getString("AnswerID");
                                                String thirdObjFromTopicID = thirdObj.getString("AnswerFromQuestID");
                                                String thirdObjContent = thirdObj.getString("AnswerContent");
                                                String thirdObjUserName = thirdObj.getString("AnswerFromUserName");
                                                String thirdObjUserID = thirdObj.getString("AnswerFromUserID");
                                                String thirdObjFavourCount = thirdObj.getString("ThumbUpCount");
                                                String thirdObjReplyCount = thirdObj.getString("ReplyCount");
                                                String thirdObjCollectCount = thirdObj.getString("UserCollectCount");
                                                boolean thirdObjIsThumbUp = thirdObj.getBoolean("IsThumbUp");
                                                boolean thirdObjIsCollect = thirdObj.getBoolean("IsCollect");
                                                addTopicReply = new TopicReply(thirdObjID,thirdObjFromTopicID,thirdObjUserID,thirdObjUserName,thirdObjContent,Integer.valueOf(thirdObjFavourCount),Integer.valueOf(thirdObjCollectCount),Integer.valueOf(thirdObjReplyCount),thirdObjIsThumbUp,thirdObjIsCollect);
                                                addTopic = new Topic(topicID,themeName,themeLogoPath,topicName,topicDesc,Integer.valueOf(topicCollectCount),Integer.valueOf(topicFavourCount),addTopicReply);
                                                topicList.add(addTopic);
                                            }
                                            else {
                                                //说明问题没有回答
                                                addTopic = new Topic(topicID,themeName,themeLogoPath,topicName,topicDesc,Integer.valueOf(topicCollectCount),Integer.valueOf(topicFavourCount));
                                                topicList.add(addTopic);
                                            }
                                            count ++;
                                        }//end if
                                        else break;
                                    }//end for
                                    //初始化count
                                    count = 0;
                                    myTopicAdapter.notifyDataSetChanged();
                                    //myTopicAdapter = new MyTopicAdapter(getActivity(),topicList,R.layout.topic_listview);
                                    //listView.setAdapter(myTopicAdapter);
                                } catch (JSONException e) {
                                    count = 0;
                                    e.printStackTrace();
                                }
                                smartRefreshLayout.finishLoadmore();
                            }
                            @Override
                            public void onStart() {
                            }
                            @Override
                            public void onFinish() {

                            }
                            @Override
                            public void onFailure(int i, String s, Throwable throwable) {
                                smartRefreshLayout.finishLoadmore();
                                showToast(getActivity(),"加载更多时，连接服务器失败");
                            }
                        });

                    }
                });
            }
        }).start();
    }
    /**
     * ToolBar显示隐藏动画
     * @param direction
     */
    public void toobarAnim(int direction) {
        //开始新的动画之前要先取消以前的动画
        if (animtor != null && animtor.isRunning()) {
            animtor.cancel();
        }
        //toolbar.getTranslationY()获取的是Toolbar距离自己顶部的距离
        float translationY=mToolbar.getTranslationY();
        if (direction == 0) {
            animtor = ObjectAnimator.ofFloat(mToolbar, "translationY", translationY, 0);
        } else if (direction == 1) {
            animtor = ObjectAnimator.ofFloat(mToolbar, "translationY", translationY, -mToolbar.getHeight());
        }
        animtor.start();
    }
    public void initHeadView() {
        View view = new View(getActivity());
        //abc_action_bar_default_height_material获取系统ActionBar的高度
        AbsListView.LayoutParams params = new AbsListView.LayoutParams
                (AbsListView.LayoutParams.MATCH_PARENT,
                        (int) getResources().getDimension(R.dimen.toolBar_height));
        view.setLayoutParams(params);
        listView.addHeaderView(view);
    }

}//end class
